package net.tribal.comic.services

import net.tribal.comic.entities.Note

class NoteService {

    boolean transactional = true

    
    /**
     * 
     * @param segment
     * @param offset
     * @param ord
     * @param sor
     * @param admin
     * @param custom
     * @return
     */
    def getActiveNotes(segment, offset, ord, sor, admin, custom) {
		ord = (ord)?  ord: "dateCreated"
		sor = (sor)?  sor: "desc"
		
		def result = [:]
		def c = Note.createCriteria()
		def results = c.list {
			if(!admin) { eq("disabled", false) }
			if(custom) { ilike("title", "%"+custom+"%") }
			
			if(offset)
				firstResult(offset)
				
			maxResults(segment)
			
			
			order(ord, sor)
		}
		
		c = Note.createCriteria()
		def total = c.count{
			if(!admin) { eq("disabled", false) }
			if(custom) { ilike("title", "%"+custom+"%") }
		}
		
		result["data"] = results
		result["count"] = total
		return result
    }
	
	
    /**
     * 
     * @param ident
     * @return
     */
	def getNote(ident) {
		return Note.get(ident)	
	}
	
	
	/**
	 * 
	 * @param instance
	 * @return
	 */
	def add( instance ) {
		instance.save()
		return instance
	}
	
	
	/**
	 * 
	 * @param instance
	 * @return
	 */
	def update( instance ) {
		if (instance.version) {
			def version = instance.version.toLong()
			if (instance.version > version) {
				noteInstance.errors.rejectValue("version", "note.optimistic.locking.failure", "Another user has updated this Note while you were editing")
				return instance
			}
		}
		
		if ( !instance.hasErrors() ) { instance.save() }
		
		return instance
	}
	
	
	/**
	 * 
	 * @param instance
	 * @return
	 */
	def delete( instance ) {
		try {
			instance.delete()
			return instance
			
		}
		catch (org.springframework.dao.DataIntegrityViolationException e) {
			instance.errors.rejectValue('',null,'error.note.delete.fault')
			return instance
		}
	}
}